import { getTabbarPages } from "@/utils/pages";
import { addQueryParams, isUrl } from "@/utils/common";

export function useRoute() {
    interface jumpOptions {
        url: string | null;
        type?: string | null;
        param?: object | [];
        callback?: Function | null;
    }

    /**
     * 跳转页面
     * @param redirect
     */
    const jumpTo = (redirect: jumpOptions) => {
        let { url, type, param, callback } = redirect;

        if (!type) {
            const tabBar = getTabbarPages();
            type = tabBar.includes(url) ? "switchTab" : "navigateTo";
        }

        if (type != "switchTab" && param && Object.keys(param).length)
            url = addQueryParams(url, param);

        switch (type) {
            case "navigateTo":
                uni.navigateTo({
                    url,
                    success: () => {
                        callback && callback();
                    },
                });
                break;
            case "switchTab":
                uni.switchTab({
                    url,
                    success: () => {
                        callback && callback();
                    },
                });
                break;
            case "reLaunch":
                uni.reLaunch({
                    url,
                    success: () => {
                        callback && callback();
                    },
                });
                break;
            case "redirectTo":
                uni.redirectTo({
                    url,
                    success: () => {
                        callback && callback();
                    },
                });
            case "navigateBack":
                uni.navigateBack({
                    url,
                    success: () => {
                        callback && callback();
                    },
                });
                break;
        }
    };

    /**
     * 跳转外链
     * @param url
     * @returns
     */
    const linkTo = (url: string) => {
        if (!url) return false;

        if (isUrl(url)) {
            // #ifdef H5
            window.location.href = url;
            // #endif

            // #ifdef MP
            jumpTo({
                url: "/pages/webview/index",
                param: { url: encodeURIComponent(url) },
            });
            // #endif
        } else {
            jumpTo({ url: url });
        }
    };

    return {
        jumpTo,
        linkTo,
    };
}
